# UI界面事件总线，用于数据交换与同步

from dataclasses import dataclass
from weakref import WeakMethod
from typing import Callable, Any
import traceback

ETYPE_NONE = 0
# 通知标签数据发生改变
ETYPE_TAG_CHANGED = 1
# 通知书签数据发生改变
ETYPE_BOOKMARK_CHANGED = 2

@dataclass
class Event:
    t: int = ETYPE_NONE
    str1: str = ""
    str2: str = ""
    int1: int = 0
    int2: int = 0
    obj: Any = None

EventHandler = Callable[[Event], None]

# 使用WeakMethod优化内存管理，组件不再被使用的时候回调应该失效，使用弱引用可以免去手动取消注册回调
event_callback_set: set[WeakMethod[EventHandler]] = set()

def send_event(event: Event):
    to_remove_set = set()
    for handler_ref in event_callback_set:
        handler = handler_ref()
        if handler:
            try:
                handler(event)
            except:
                traceback.print_exc()
        else:
            to_remove_set.add(handler_ref)
    # 清理失效的回调引用
    for handler_ref in to_remove_set:
        event_callback_set.remove(handler_ref)

def register_handler(handler: EventHandler):
    event_callback_set.add(WeakMethod(handler))
